<template>
	<view class="goods-detail">
		<van-toast id="van-toast" />
		<!-- 商品介绍图片轮播区域 -->
		<swiper class="img-area" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" :circular="true">
			<swiper-item v-for="(item, index) in goodsDetailObj.goodsImgIntro" :key="index">
				<image :src="item" @click="previewImg(goodsDetailObj.goodsImgIntro)"></image>
			</swiper-item>
		</swiper>
		<!-- 商品选项区域 -->
		<view class="goods-info-area">
			<text>&yen;<text class="goods-price">{{ goodsDetailObj.goodsPrice.toFixed(2) }}</text></text>
			<text class="goods-name">{{ goodsDetailObj.goodsName }}</text>
			<!-- 商品属性及属性选项值弹出层 -->
			<van-cell :label="chosenChoiceName" title="请选择商品分类" is-link @click="editChosenChoice" center />
		</view>
		<!-- 评价区域 -->
		<view class="comment-area">
			<van-cell title="评价" is-link :url="'/subpages/commentlist/commentlist?gid=' + goodId" />
			<shop-comment :commentlist="commentList"></shop-comment>
		</view>
		<!-- 店铺信息展示区域 -->
		<view class="merchant-info">
			<view class="merchant-title">
				<image :src="merchantInfo.photo"></image>
				<text class="merchant-name">{{ merchantInfo.merchantsname }}</text>
			</view>
			<view class="merchant-settle">
				<view>
					<text>{{ merchantInfo.num }}</text>
					<text>粉丝人数</text>
				</view>
				<view></view>
				<view>
					<text>{{ merchantInfo.goodsnum }}</text>
					<text>全部商品</text>
				</view>
			</view>
			<view class="btn-area">
				<van-button round type="info" @click="favThisMerchant">关注店铺</van-button>
				<van-button round type="info" @click="gotoMechantIndex">进入店铺</van-button>
			</view>
		</view>
		<!-- 商品详情图片展示区域 -->
		<view>
			<rich-text :nodes="goodsDetailObj.goodsImgInfo"></rich-text>
		</view>
		<!-- 商品底部导航区 -->
		<van-goods-action>
			<van-goods-action-icon icon="star-o" text="收藏" @click="collectCurrentGood"/>
		  <van-goods-action-icon icon="chat-o" text="客服"/>
		  <van-goods-action-icon icon="cart-o" text="购物车" @click="navigateToCart"/>
		  <van-goods-action-button text="加入购物车" type="warning" @click="addToCart"/>
		  <van-goods-action-button text="立即购买" @click="buyNow"/>
		</van-goods-action>
		<!-- 商品属性选项值区域 -->
		<van-popup
		  :show="isShow"
			position="bottom"
			custom-style="height: 80%;padding: 30rpx;overflow: scroll;"
			@close="closeEditTab"
			closeable round>
			<view class="popup-top-area">
				<text v-if="choiceInven[0] && choiceInven[0].headroom > 0" class="goods-price">&yen; {{ goodsDetailObj.goodsPrice.toFixed(2) }}</text>
				<text v-else>无货</text>
				<van-cell :label="chosenChoiceName" title="已选商品分类" center />
			</view>
			<view class="attr-choice-area">
				<van-radio-group v-for="(item, index) in goodsDetailObj.attrAndChoice" :key="item.attrid" :value="chosenChioceId[index]" @change="choiceChange(index, $event)">
					<text>{{ item.attrname }}</text>
					<block v-for="val in item.children" :key="val.choiceid">
						<van-radio :name="val.choiceid + ''">{{ val.choicename }}</van-radio>
					</block>
				</van-radio-group>
			</view>
			<!-- 商品数量区域 -->
			<view class="count-area">
				<text>数量</text>
				<van-stepper :value="count" integer min="1" max="5" @change="changeNum"/>
			</view>
		</van-popup>
	</view>
</template>

<script>
	import Toast from '../../wxcomponents/vant-weapp/toast/toast.js'
	export default {
		onLoad(state) {
			this.goodId = state.id
			this.merchantId = state.mid
			this.choiceInven = []
			this.getGoodDetailById()
			this.getAttrChoiceById()
			this.getComment()
			this.getMechantInfo()
			// 将当前的商品id值追加到本地存储中的history键值中
			const arr = JSON.parse(uni.getStorageSync('history'))
			arr.unshift(this.goodId)
			// 历史记录最多保存200条
			if(arr.length >= 200) arr.splice(arr.length - 1, 1)
			uni.setStorageSync('history', JSON.stringify([...new Set(arr)]))
		},
		data() {
			return {
				// 商家id
				merchantId: 0,
				// 商品id
				goodId: 0,
				// 控制是否展示商品属性及选项值的变量
				isShow: false,
				// 商品属性选项值被选中的标识
				chosenChioceId: [],
				// 商家详细信息对象
				merchantInfo: {},
				// 商品的详细信息对象
				goodsDetailObj: {
					// 存储单个商品的详细介绍图片信息
					goodsImgIntro: [],
					// 商品的名称
					goodsName: '',
					// 商品价格
					goodsPrice: 0,
					// 该商品属性及选项值
					attrAndChoice: [],
					// 上市日期
					shelveDate: '',
					// 商品下方详细展示区
					goodsImgInfo: ''
				},
				// 被激活选项值的选项值名和价格差
				activeChoiceNameAndPrice: [],
				// 商品基价
				basePrice: 0,
				// 用户选中的商品属性选项值
				chosenChoiceName: '',
				// 商品评论列表
				commentList: [],
				// 商品在该属性选项值下的库存
				choiceInven: [],
				// 商品数量
				count: 1
			}
		},
		watch: {
			activeChoiceNameAndPrice(newValue, oldVlue) {
				let sum = 0
				this.chosenChoiceName = ''
				newValue.forEach(item => {
					sum += item.choiceprice
					this.chosenChoiceName += item.choicename + ' '
				})
				this.goodsDetailObj.goodsPrice = this.basePrice + sum
			}
		},
		methods: {
			// 根据商品id获取商品的详细信息
			async getGoodDetailById() {
				const { data: res } = await uni.$http.get('/goods/detail', { id: this.goodId })
				if(res.meta.status !== 200) return Toast.fail(res.meta.message)
				this.basePrice = res.recordsets[1][0].goodsbaseprice
				// 向商品详细对象中添加此商品的价格，名字等属性
				this.goodsDetailObj.goodsImgIntro = res.recordset.find(item => item['goodsdetailimg']).goodsdetailimg.split(';')
				this.goodsDetailObj.goodsName = res.recordsets[1][0].goodsname
				this.goodsDetailObj.goodsPrice = res.recordsets[1][0].goodsbaseprice
				this.goodsDetailObj.shelveDate = res.recordsets[1][0].shelvesdate
				this.goodsDetailObj.goodsImgInfo = res.recordsets[1][0].goodsimginfo
				console.log(res.recordsets[2])
				for(let item of res.recordsets[2]) {
					// 如果attrAndChoice中没有此节点，需要加入新的对象包含这个商品属性
					if(!this.goodsDetailObj.attrAndChoice.find(val => val.attrid === item.attrid)) {
						this.goodsDetailObj.attrAndChoice.push({
							attrid: item.attrid,
							attrname: item.attrname,
							children: [{
								choiceid: item.choiceid,
								choicename: item.choicename,
								choiceprice: item.choiceprice
							}]
						})
					} else {
						// 如果attrAndChoice中已经有该商品的属性id 直接加入此id的children节点中
						const index = this.goodsDetailObj.attrAndChoice.findIndex(val => val.attrid === item.attrid)
						this.goodsDetailObj.attrAndChoice[index].children.push({
							choiceid: item.choiceid,
							choicename: item.choicename,
							choiceprice: item.choiceprice
						})
					}
				}
			},
			// 获取商品属性选项值信息
			async getAttrChoiceById() {
				if(this.chosenChioceId.filter(item => item !== undefined).length < this.goodsDetailObj.attrAndChoice.length) return
				const { data: res } = await uni.$http.get('/attr/choice', { id: this.chosenChioceId.join(',') })
				if(res.meta.status !== 200) return Toast.fail(res.meta.message)
				this.activeChoiceNameAndPrice = res.recordset
			},
			// 根据商品id获取评论
			async getComment() {
				const { data: res } = await uni.$http.get('/comment', { gid: this.goodId, num: 3 })
				if(res.meta.status !== 200) return Toast.fail('暂无评论')
				this.commentList = res.recordset
			},
			// 根据商品id和商品属性选项值id获取商品的库存信息
			async getGoodInventory() {
				const { data: res } = await uni.$http.get('/goods/inven', { gid: this.goodId, cid: this.chosenChioceId.join(',')})
				if(res.meta.status !== 200) return Toast.fail(res.meta.message)
				this.choiceInven = res.recordset
			},
			// 根据商家id获取商家信息
			async getMechantInfo() {
				const { data: res } = await uni.$http.get('/merchant/detail', { id: this.merchantId })
				if(res.meta.status !== 200) return Toast.fail(res.meta.message)
				this.merchantInfo = res.recordset[0]
				console.log(this.merchantInfo)
			},
			// 点击cell单元格弹出商品属性选项时触发时触发 展示选择弹出框
			editChosenChoice() {
				this.isShow = true
			},
			// 关闭弹出框时触发
			closeEditTab() {
				this.isShow = false
			},
			// 商品属性选项值发生变化时触发
			choiceChange(index, e) {
				this.chosenChioceId[index] = e.detail
				this.getAttrChoiceById()
				this.chosenChoiceName = ''
				this.getGoodInventory()
			},
			// 图片被点击时触发预览图片
			previewImg(urls) {
				uni.previewImage({
					urls
				})
			},
			// 加入购物车被点击时触发
			async addToCart() {
				// 判断用户是否选择商品属性
				if(this.chosenChioceId.filter(item => item !== undefined).length < this.goodsDetailObj.attrAndChoice.length) return Toast.fail('请选择商品分类')
				// 判断用户是否登录
				if(!uni.getStorageSync('uid')) return uni.showModal({
					title: '提示',
					content: '您还未登录，是否前往登录',
					cancelText: '取消',
					confirmText: '确定',
					success(res) {
						if(res.confirm) { uni.switchTab({
							url: '../../pages/my/my'
						}) } else if(res.cancel) {
							console.log('取消按钮')
						}
					}
				})
				if(this.choiceInven.length === 0 || this.choiceInven[0].headroom <= 0) return Toast.fail('该分类无货!')
				// 如果用户已选择商品属性并且已经登陆  调用接口将此类商品添加至购物车
				const { data: res } = await uni.$http.post('/cart/add', {
						uid: uni.getStorageSync('uid'),
						gid: this.goodId,
						num: this.count,
						aid: this.goodsDetailObj.attrAndChoice.map(item => item.attrid).join(','),
						cid: this.chosenChioceId.join(','),
						price: this.goodsDetailObj.goodsPrice
					})
				if(res.meta.status !== 200) return Toast.fail(res.meta.message)
				Toast.success('加入购物车成功')
			},
			// 购物车按钮被点击时触发 跳转至购物车界面
			navigateToCart() {
				uni.switchTab({
					url: '../../pages/cart/cart'
				})
			},
			// 商品数量发生变化时触发
			changeNum(e) {
				this.count = e.detail
			},
			// 立即购买按钮被点击时触发  跳转至生成订单界面
			buyNow() {
				if(this.chosenChioceId.length !== this.goodsDetailObj.attrAndChoice.length) return Toast.fail('请选择商品分类')
				if(this.choiceInven.length === 0 || this.choiceInven[0].headroom <= 0) return Toast.fail('该分类无货!')
				uni.navigateTo({
					url: `/subpages/ordersgenerate/ordersgenerate?type=0&gid=${ this.goodId }&cid=${ this.chosenChioceId }&cname=${ this.chosenChoiceName }&price=${ this.goodsDetailObj.goodsPrice }&img=${ this.goodsDetailObj.goodsImgIntro[0] }&gname=${ this.goodsDetailObj.goodsName }&num=${ this.count }&mid=${ this.merchantInfo.merchantsid }&mname=${ this.merchantInfo.merchantsname }`
				})
			},
			// 用户收藏此商品 发起请求添加商品
			async collectCurrentGood() {
				const { data: res } = await uni.$http.post('/user/addfavgood', { uid: uni.getStorageSync('uid'), gid: this.goodId })
				if(res.meta.status !== 200) return Toast.fail(res.meta.message)
				Toast.success('收藏成功')
			},
			// 当进入店铺被点击时 跳转至店铺详情页
			gotoMechantIndex() {
				uni.navigateTo({
					url: '/subpages/merchantindex/merchantindex?mid=' + this.merchantId
				})
			},
			// 关注店铺按钮被点击时触发
			async favThisMerchant() {
				console.log('haha')
				const { data: res } = await uni.$http.post('/user/favadd', { uid: uni.getStorageSync('uid'), mid: this.merchantId } )
				if(res.meta.status !== 200) return Toast.fail(res.meta.message)
				Toast.success('关注成功')
				this.getMechantInfo()
			}
		}
	}
</script>

<style>
	page {
		background-color: #f2f2f2;
	}
	
	.goods-detail {
		padding: 0 0 100rpx 0;
	}
	
	.img-area,
	.img-area image {
		width: 100%;
		height: 750rpx;
		background-color: #fff;
	}
	
	.goods-info-area {
		width: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		background-color: #fff;
		padding: 20rpx;
	} 
	
	.goods-name {
		margin: 10rpx 0;
	}
	
	.goods-price {
		font-size: 20px;
		color: red;
		padding: 0 10rpx;
	}
	
	.attrchoice-area {
		height: 100rpx;
		line-height: 100rpx;
		font-size: 14px;
	}
	
	.van-rate {
		margin-left: 5rpx;
		height: 38rpx;
	}
	
	.van-rate__item {
		float: left;
	}
	
	.comment-area {
		margin: 20rpx 0;
		background-color: #fff;
	}
	
	.merchant-info {
		background-color: #fff;
		padding: 20rpx;
	}
	
	.merchant-title {
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}
	
	.merchant-title image {
		width: 80rpx;
		height: 80rpx;
		margin: 0 15rpx;
	}
	
	.merchant-settle {
		display: flex;
		justify-content: space-around;
		align-items: center;
		padding: 40rpx 0;
	}
	
	.btn-area {
		display: flex;
		justify-content: space-around;
	}
	
	.btn-area > button {
		border: 1px solid #b5b5b5;
		background-color: #fff;
		font-size: 14px;
		border-radius: 20px;
	}
	
	.goodattr text {
		border: 1px solid skyblue;
		margin: 20rpx;
	}
	
	.tabbar-bottom {
		display: flex;
		align-items: center;
	}
	
	.van-radio {
		padding: 20rpx 0;
	}
	
	.user-name {
		font-size: 12px;
	}
	
	.count-area {
		display: flex;
		justify-content: space-between;
		padding: 20rpx 0;
	}
	
	.van-cell__title {
		font-size: 16px;
		font-weight: 500;
	}
	
	.merchant-settle > view {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
	
	.merchant-settle view:nth-child(2) {
		width: 5px;
		height: 50px;
		background-color: #f3f3f3;
	}
	
	.merchant-settle > view text:last-child {
		color: #999;
		font-size: 10px;
	}
	</style>
